package com.heima.behavior.service.impl;

import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 单机的mongo不支持事务
     * 在副本集群的情况下才支持事务
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //1,先判断userId，存在的话先判断userId行为实体数据
        if (userId != null) {
            //如果为空添加行为实体数据
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(ApBehaviorEntry.Type.USER));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);

            if (behaviorEntry == null) {
                behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                behaviorEntry.setRefId(userId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        //2,如果userId查不到就使用设备Id查询，存在的话先判断userId行为实体数据
        if (equipmentId != null) {
        //如果为空，就添加设备Id数据
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);

            if (behaviorEntry == null) {
                behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                behaviorEntry.setRefId(equipmentId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        return null;
    }
}
